package com.msb.servicepassengeruser.service;

import com.msb.internalcommon.constant.CommonStatusEnum;
import com.msb.internalcommon.dto.ResponseResult;
import com.msb.internalcommon.dto.PassengerUser;
import com.msb.servicepassengeruser.mapper.PassengerUserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Auther: WuWen
 * @Date: 2023/3/14 - 03 - 14 - 11:21
 * @Description: com.msb.servicepassengeruser.service
 * @version: 1.0
 */
@Service
public class UserService {

    @Autowired
    private PassengerUserMapper passengerUserMapper;


    public ResponseResult loginOrRegister(String passengerPhone){


        System.out.println("UserService被调用，手机号：" + passengerPhone);
        // 根据手机号查询用户信息
        Map<String, Object> user = new HashMap<>();
        user.put("passenger_phone", passengerPhone);
        List<PassengerUser> passengerUsers = passengerUserMapper.selectByMap(user);


        // 判断用户信息是否存在
        // System.out.println(passengerUsers.isEmpty()?"无信息":passengerUsers.get(0).getPassengerPhone());

        // 不存在 则创建
        if(passengerUsers.isEmpty()){
            PassengerUser passengerUser = new PassengerUser();
            passengerUser.setPassengerName("张三");
            passengerUser.setPassengerGender((byte)0);
            passengerUser.setState((byte)0);

            passengerUser.setPassengerPhone(passengerPhone);

            LocalDateTime time = LocalDateTime.now();
            passengerUser.setGmtCreate(time);
            passengerUser.setGmtModified(time);

            passengerUserMapper.insert(passengerUser);
        }

        return ResponseResult.success();
    }

    /**
     * 根据手机号查询用户信息
     * @param passengerPhone
     * @return
     */
    public ResponseResult getUserByPhone(String passengerPhone){

        // 根据手机号查询用户信息
        Map<String, Object> user = new HashMap<>();
        user.put("passenger_phone", passengerPhone);
        List<PassengerUser> passengerUsers = passengerUserMapper.selectByMap(user);

        System.out.println("getUserByPhone");

        if (passengerUsers.size()==0){
            return ResponseResult.fail(CommonStatusEnum.USER__NOT_EXITS.getCode(),CommonStatusEnum.USER__NOT_EXITS.getValue());
        }else {
            PassengerUser passengerUser = passengerUsers.get(0);
            return ResponseResult.success(passengerUser);
        }

    }
}
